package com.linxz.framework.utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

/**
 * @author Linxz
 * 创建日期：2019年10月26日 20:02
 * version：v4.5.4
 * 描述：
 */
public class WebViewBiz {

    private WebView webView;
    private ProgressBar progressBar;
    private String url;
    private boolean loadError;
    private OnLoadSuccessListener onLoadSuccessListener;
    private OnLoadErrorListener onLoadErrorListener;
    private ReceivedTitle mReceivedTitle;

    private WebViewBiz(WebView webView,
                       String url,
                       ProgressBar progressBar,
                       OnLoadSuccessListener onLoadSuccessListener,
                       OnLoadErrorListener onLoadErrorListener,
                       ReceivedTitle receivedTitle) {
        this.webView = webView;
        this.url = url;
        this.progressBar = progressBar;
        this.onLoadSuccessListener=onLoadSuccessListener;
        this.onLoadErrorListener=onLoadErrorListener;
        this.mReceivedTitle=receivedTitle;
        if (this.webView==null){
            throw new IllegalArgumentException("webView不能为空");
        }
        initWebView();
        setListener();
        loadUrl();
    }

    public static Builder builder(){
        return new Builder();
    }

    public static class Builder {
        private WebView webView;
        private ProgressBar progressBar;
        private String url;
        private OnLoadSuccessListener onLoadSuccessListener;
        private OnLoadErrorListener onLoadErrorListener;
        private ReceivedTitle receivedTitle;

        public Builder setWebView(WebView webView) {
            this.webView = webView;
            return this;
        }

        public Builder setUrl(String url) {
            this.url = url;
            return this;
        }

        public Builder setProgressBar(ProgressBar progressBar) {
            this.progressBar = progressBar;
            return this;
        }

        public Builder setOnLoadSuccessListener(OnLoadSuccessListener listener){
            this.onLoadSuccessListener=listener;
            return this;
        }

        public Builder setonLoadErrorListener(OnLoadErrorListener listener){
            this.onLoadErrorListener=listener;
            return this;
        }

        public Builder setReceivedTitle(ReceivedTitle receivedTitle){
            this.receivedTitle=receivedTitle;
            return this;
        }

        public WebViewBiz build() {
            return new WebViewBiz(webView, url, progressBar,onLoadSuccessListener,onLoadErrorListener,receivedTitle);
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true); // 默认false，设置true后我们才能在WebView里与我们的JS代码进行交互
        settings.setJavaScriptCanOpenWindowsAutomatically(true); // 设置JS是否可以打开WebView新窗口
        settings.setSupportZoom(true); // 支持缩放
        settings.setBuiltInZoomControls(true); // 支持手势缩放
        settings.setDisplayZoomControls(false); // 不显示缩放按钮
        settings.setDatabaseEnabled(true);//数据库存储API是否可用，默认值false。
        settings.setSaveFormData(true);//WebView是否保存表单数据，默认值true。
        settings.setDomStorageEnabled(true);//DOM存储API是否可用，默认false。
        settings.setGeolocationEnabled(true);//定位是否可用，默认为true。
        settings.setAppCacheEnabled(true);//应用缓存API是否可用，默认值false, 结合setAppCachePath(String)使用。
        settings.setUseWideViewPort(true); // 将图片调整到适合WebView的大小
        settings.setLoadWithOverviewMode(true); // 自适应屏幕
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//加上这一句可以在webview中加载https图片，否则加载不出来
        }
        webView.setHorizontalScrollBarEnabled(false);//去掉webview的滚动条,水平不显示
        webView.setScrollbarFadingEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER); // 取消WebView中滚动或拖动到顶部、底部时的阴影
    }

    public void loadUrl(String url){
        this.url=url;
        webView.loadUrl(this.url);
    }

    private void loadUrl(){
        if (!TextUtils.isEmpty(url)){
            webView.loadUrl(url);
        }
    }


    private void setListener() {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
                if (!loadError){
                    if (onLoadSuccessListener!=null){
                        onLoadSuccessListener.onLoadSuccess();
                    }
                }
                loadError=false;
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                super.onReceivedError(webView, i, s, s1);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
                loadError=true;
                if (onLoadErrorListener!=null){
                    onLoadErrorListener.onLoadError();
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.isForMainFrame()){
                        loadError=true;
                        if (onLoadErrorListener!=null){
                            onLoadErrorListener.onLoadError();
                        }
                    }
                }

                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (progressBar==null){
                    return;
                }
                if (newProgress >= 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    if (progressBar.getVisibility() == View.GONE) {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                    progressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(!TextUtils.isEmpty(title)&&title.toLowerCase().contains("error")){
                    loadError = true;
                    if (onLoadErrorListener!=null){
                        onLoadErrorListener.onLoadError();
                    }
                }else{
                    mReceivedTitle.onReceivedTitle(view,title);
                }
            }
        });
    }


    public boolean goBack(){
        if (webView==null){
            return false;
        }
        if (webView.canGoBack()){
            webView.goBack();
            return true;
        }
        return false;
    }

    @SuppressLint("SetJavaScriptEnabled")
    public void onResume(){
        if (webView!=null){
            webView.getSettings().setJavaScriptEnabled(true);
            webView.onResume();
        }
    }

    public void onPause(){
        if (webView!=null){
            webView.getSettings().setJavaScriptEnabled(false);
            webView.onPause();
        }
    }

    public void onDestroy(){
        if (webView!=null){
            webView.setVisibility(View.GONE);
            webView.destroy();
        }
    }

    public interface OnLoadSuccessListener{
        void onLoadSuccess();
    }

    public interface OnLoadErrorListener{
        void onLoadError();
    }

    public interface ReceivedTitle{
        void onReceivedTitle(WebView view, String title);
    }
}

